package lol.clann.bukkit.pluginboot.config.jackson.item;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import lol.clann.bukkit.pluginboot.util.ItemStackUtils;
import lol.clann.bukkit.pluginboot.util.NBTUtils;
import lol.clann.clannboot.annotation.inject.Inject;
import lol.clann.clannboot.annotation.svc.PostInstance;
import lol.clann.clannboot.annotation.svc.Service;
import lol.clann.clannboot.config.jackson.Jackson;
import org.bukkit.inventory.ItemStack;

import java.io.IOException;

/**
 * @author pyz
 * @date 2018/10/12 下午8:20
 */
@Service(priority = Integer.MAX_VALUE - 100)
public class ItemStackDeserializer {
    @Inject
    private ItemStackUtils itemStackUtils;
    @Inject
    private ObjectMapper objectMapper;

    @PostInstance
    private void init() {
        Jackson.addDeserializer(ItemStackUtils.classNMSItemStack.getHandle(), new JsonDeserializer<Object>() {
            @Override
            public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                Object tag = objectMapper.readValue(p, NBTUtils.classNBTTagCompound.getHandle());
                ItemStack itemStack = itemStackUtils.fromCompound(tag);
                return itemStackUtils.toNMS(itemStack);
            }
        });
        Jackson.addDeserializer(ItemStack.class, new JsonDeserializer<ItemStack>() {
            @Override
            public ItemStack deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                Object tag = objectMapper.readValue(p, NBTUtils.classNBTTagCompound.getHandle());
                ItemStack itemStack = itemStackUtils.fromCompound(tag);
                return itemStack;
            }
        });
    }
}
